package com.frogs.ucenter.controller;

import java.util.Arrays;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.data.repository.query.Param;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;

import com.alibaba.fastjson.JSONObject;
import com.frogs.framework.base.web.BaseController3;
import com.frogs.framework.web.HttpRequestInfo;
import com.frogs.system.util.ApiUrlParamEnum;
import com.frogs.system.web.api.response.Response.ApiResultEnum;
import com.frogs.system.web.api.response.Response.ResultParamEnum;
import com.frogs.ucenter.component.UserPermissionHelper;
import com.frogs.ucenter.entity.UserBaseAccountInfo;
import com.frogs.ucenter.entity.UserShippingAddress;
import com.frogs.ucenter.service.UserService;
import com.frogs.ucenter.service.UserShippingAddressService;
import com.frogs.ucenter.util.SysStatusEnum;

@Controller("userShippingAddressController")
public class UserShippingAddressController extends BaseController3 {

	private static Logger log = LoggerFactory.getLogger(UserShippingAddressController.class);
	
	private static final String EDIT_VIEW = "address/edit";
	private static final String HOME_VIEW = "address/index";
	
	private static final String EDIT = "/address/edit";
	private static final String MERGE = "/address/merge";
	private static final String LIST = "/address/list";
	private static final String DELETE = "/address/delete";
	private static final String DEFAULT = "/address/default";
	private static final String SHOW = "/address/show";
	private static final String HOME = "/address/index";
	
	@Resource
	private UserPermissionHelper userPermissionHelper;
	
	@Resource(name="userShippingAddressService")
	private UserShippingAddressService userShippingAddressService;
	
	@Resource
	private UserService userService;
    
    @RequestMapping(LIST)
    public JSONObject listUserShippingAddress(@Param("pn") Integer pageNo,@Param("pz") Integer pageSize ,HttpServletRequest request) throws Exception {
    	try {
    		
        	UserBaseAccountInfo user = userPermissionHelper.getUser(request);
        	if(null == pageNo || pageNo == 0) {
        		pageNo = 1;
        	}
        	
        	if(null == pageSize || pageSize == 0) {
        		pageSize = 200;
        	}
        	
        	if(user.getId() < 0) {
        		throw new Exception("用户不存在!");
        	}
			return userShippingAddressService.getUserAddressList(pageNo, pageSize, user.getId());
		} catch (Exception e) {
			log.error("func[listUserShippingAddress] parameterMap[{}] exception[{} - {}] desc[fail]",//
					new Object[] { request.getParameterMap(), e.getMessage(), Arrays.deepToString(e.getStackTrace()) });
			
			request.setAttribute("errorMessage", e.getMessage());
		}
    	return null;
    }
    
    @RequestMapping(HOME)
    public String home(@Param("pn") Integer pageNo,@Param("pz") Integer pageSize , HttpServletRequest request, ModelMap model) {
    	
		
    	UserBaseAccountInfo user = userPermissionHelper.getUser(request);
    	if(null == pageNo || pageNo == 0) {
    		pageNo = 1;
    	}
    	
    	if(null == pageSize || pageSize == 0) {
    		pageSize = 200;
    	}
    	
    	if(user.getId() < 0) {
    		model.put(ResultParamEnum.tip.getParamName(), SysStatusEnum.NOT_LOGIN_ERR.getMsg());
			model.put(ResultParamEnum.code.getParamName(), SysStatusEnum.NOT_LOGIN_ERR.getCode());
			return ERROR_VIEW;
    	}
    	
    	
    	try {
    		//加载用户基础信息
			model.put("userInfo", userService.getUserBaseInfoForMap(user.getId()));
			//加载用户地址信息
	    	model.put("addressList", userShippingAddressService.getUserAddressListForList(pageNo, pageSize, user.getId()));
		} catch (Exception e) {
			log.error("func[home] parameterMap[{}] exception[{} - {}] desc[fail]",//
					new Object[] { request.getParameterMap(), e.getMessage(), Arrays.deepToString(e.getStackTrace()) });
			
			request.setAttribute("errorMessage", e.getMessage());
			return ERROR_VIEW;
		}
    	
    	return HOME_VIEW;
    }
    
    @RequestMapping(EDIT)
	public String editBaseInfo(HttpServletRequest request) {
		try {
			return EDIT_VIEW;
		} catch (Exception e) {
			log.error("func[editBaseInfo] parameterMap[{}] exception[{} - {}] desc[fail]",//
					new Object[] { request.getParameterMap(), e.getMessage(), Arrays.deepToString(e.getStackTrace()) });
			request.setAttribute("errorMessage", e.getMessage());
			return ERROR_VIEW;
		}
	}

    @RequestMapping(MERGE)
    public JSONObject updateUserShippingAddress(HttpServletRequest request, ModelMap model, UserShippingAddress userShippingAddressNew) throws Exception {
    	JSONObject resultJson = new JSONObject();
    	JSONObject response = new JSONObject();
    	try {
    		UserBaseAccountInfo user = userPermissionHelper.getUser(request);
    		int addrId = (null == userShippingAddressNew.getId()) ? 0 : userShippingAddressNew.getId();
    		
			
    		if(null == user) {
    			response.put("code", ApiResultEnum.FAIL.getId());
    			response.put("tip", "无法识别用户");
    			
    			resultJson.put("response", response);
    			return resultJson;
    		}
    		if(addrId <= 0) {
    			resultJson = userShippingAddressService.addUserAddress(user.getId(), userShippingAddressNew);
    		} else {
    			resultJson = userShippingAddressService.updateUserAddress(user.getId(), userShippingAddressNew);
    		}
    		return resultJson;
    		
		} catch (Exception e) {
			log.error("func[updateUserShippingAddress] parameterMap[{}] exception[{} - {}] desc[fail]",//
					new Object[] { request.getParameterMap(), e.getMessage(), Arrays.deepToString(e.getStackTrace()) });
			response.put("code", ApiResultEnum.FAIL.getId());
			response.put("tip", "保存收货地址失败！");
			resultJson.put("response", response);
		}
		return resultJson;
    }
    
    @RequestMapping(DELETE)
    public JSONObject deleteUserShippingAddress(HttpServletRequest request,HttpServletResponse response, ModelMap model, UserShippingAddress userShippingAddressNew) throws Exception {
    	try {
    		HttpRequestInfo requestInfo = new HttpRequestInfo(request);
    		UserBaseAccountInfo user = userPermissionHelper.getUser(request);
    		
			
    		
    		int addrId = requestInfo.getIntParameter(ApiUrlParamEnum.userShippingAddressId.getParamName(), -1);
    		if(null == user || addrId < 0) {
    			model.put(ResultParamEnum.tip.getParamName(), SysStatusEnum.USER_ID_ERR.getMsg());
				model.put(ResultParamEnum.code.getParamName(), SysStatusEnum.USER_ID_ERR.getCode());
				return null;
    		}
    		int userId = user.getId();
    		JSONObject jso = userShippingAddressService.deleteUserAddress(userId, addrId);
    		return jso;
		} catch (Exception e) {
			log.error("func[deleteUserShippingAddress] parameterMap[{}] exception[{} - {}] desc[fail]",//
					new Object[] { request.getParameterMap(), e.getMessage(), Arrays.deepToString(e.getStackTrace()) });
		}
    	return null;
    }
    
    @RequestMapping(DEFAULT)
    public JSONObject defaultUserShippingAddress(HttpServletRequest request,HttpServletResponse response, ModelMap model, UserShippingAddress userShippingAddressNew) throws Exception {
    	try {
    		HttpRequestInfo requestInfo = new HttpRequestInfo(request);
    		UserBaseAccountInfo user = userPermissionHelper.getUser(request);
    		
    		
    		int addrId = requestInfo.getIntParameter(ApiUrlParamEnum.userShippingAddressId.getParamName(), -1);
    		
    		if(null == user || addrId < 0) {
    			model.put(ResultParamEnum.tip.getParamName(), SysStatusEnum.USER_ID_ERR.getMsg());
    			model.put(ResultParamEnum.code.getParamName(), SysStatusEnum.USER_ID_ERR.getCode());
    			return null;
    		}
    		int userId = user.getId();
    		JSONObject jso = userShippingAddressService.defaultUserAddress(userId, addrId);
    		return jso;
    	} catch (Exception e) {
    		log.error("func[defaultUserShippingAddress] parameterMap[{}] exception[{} - {}] desc[fail]",//
    				new Object[] { request.getParameterMap(), e.getMessage(), Arrays.deepToString(e.getStackTrace()) });
    	}
    	return null;
    }
    
    @RequestMapping(SHOW)
    public JSONObject showUserShippingAddress(HttpServletRequest request,HttpServletResponse response, ModelMap model, UserShippingAddress userShippingAddressNew) throws Exception {
    	try {
    		HttpRequestInfo requestInfo = new HttpRequestInfo(request);
    		UserBaseAccountInfo user = userPermissionHelper.getUser(request);
    		
    		
    		int addrId = requestInfo.getIntParameter(ApiUrlParamEnum.userShippingAddressId.getParamName(), -1);
    		
    		if(null == user || addrId < 0) {
    			model.put(ResultParamEnum.tip.getParamName(), SysStatusEnum.USER_ID_ERR.getMsg());
    			model.put(ResultParamEnum.code.getParamName(), SysStatusEnum.USER_ID_ERR.getCode());
    			return null;
    		}
    		int userId = user.getId();
    		JSONObject jso = userShippingAddressService.showUserAddress(userId, addrId);
    		return jso;
    	} catch (Exception e) {
    		log.error("func[showUserShippingAddress] parameterMap[{}] exception[{} - {}] desc[fail]",//
    				new Object[] { request.getParameterMap(), e.getMessage(), Arrays.deepToString(e.getStackTrace()) });
    	}
    	return null;
    }
}